package com.yookey.study.adapter;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Created by jp on 2017/8/9.
 */

public class CustomDivider extends RecyclerView.ItemDecoration {
    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
    private Drawable mDivider;
    private CustomDraw mCustomDraw;

    public void setCustomDraw(CustomDraw customDraw) {
        mCustomDraw = customDraw;
    }

    public CustomDivider(Context context) {
        TypedArray typedArray = context.obtainStyledAttributes(ATTRS);
        mDivider = typedArray.getDrawable(0);
        typedArray.recycle();
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        drawLine(c, parent);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
//        if (mCustomDraw != null) {
//            if (!mCustomDraw.shouldDraw(parent.getAdapter().getItemViewType(parent.getChildAdapterPosition(view)))) {
//                super.getItemOffsets(outRect, view, parent, state);
//                return;
//            }
//        }
//        outRect.set(0, 0, -1, -1);
        outRect.set(0, 0, 0, 0);

    }


    private void drawLine(Canvas c, RecyclerView parent) {

        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            if (mCustomDraw != null) {
                boolean b = mCustomDraw.shouldDraw(parent.getAdapter().getItemViewType(parent.getChildAdapterPosition(child)));
                if (!b) {
                    continue;
                }
            }

            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
            int left = child.getRight() + layoutParams.rightMargin - 1;
            int right = left + 1;
            int top = child.getTop() + layoutParams.topMargin;
            int bottom = child.getBottom() + layoutParams.bottomMargin;
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
            left = child.getLeft() - layoutParams.leftMargin;
            right = child.getRight() + layoutParams.rightMargin;
            top = child.getBottom() + layoutParams.bottomMargin - 1;
            bottom = top + 1;
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    public interface CustomDraw {
        boolean shouldDraw(int type);
    }

}
